import logging

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class Player(db.Model):
  player = db.StringProperty(required=True)
  rank = db.FloatProperty(required=True)

class Game(db.Model):
  black_player = db.ReferenceProperty(Player, required=True, collection_name='black_player_games_set')
  white_player = db.ReferenceProperty(Player, required=True, collection_name='white_player_games_set')
  black_score = db.IntegerProperty(required=True)
  white_score = db.IntegerProperty(required=True)
  handicap = db.IntegerProperty(default=0, validator=lambda x: x >= 0)

class ViewLadder(webapp.RequestHandler):
  def get(self):  
    players = db.GqlQuery('SELECT * FROM Player ORDER BY rank')
    template_values = {'players': players}
    self.response.out.write(template.render('ladder.html', template_values))

class AddPlayer(webapp.RequestHandler):
  def get(self):
    template_values = {}
    self.response.out.write(template.render('addplayer.html', template_values))
    
  def post(self): 
    player = Player(player=self.request.get('player'),
                    rank=float(self.request.get('rank')))
    player.put()
    logging.info('Added player: %s of rank %d.' % (player.player, player.rank))
    template_values = {'player': player}
    self.response.out.write(template.render('addplayer.html', template_values))
    
class AddGame(webapp.RequestHandler):
  def get(self):
    template_values = {}
    self.response.out.write(template.render('addgame.html', template_values))
    
  def post(self):
    black_player = db.GqlQuery('SELECT * FROM Player WHERE player=:player',
                               player=self.request.get('black_player'))[0]
    white_player = db.GqlQuery('SELECT * FROM Player WHERE player=:player',
                               player=self.request.get('white_player'))[0]
    game = Game(black_player=black_player.key(),
                white_player=white_player.key(),
                black_score=int(self.request.get('black_score')),
                white_score=int(self.request.get('white_score')),
                handicap=int(self.request.get('handicap')))
    game.put()
    logging.info('Added game between black %s and white %s, score %s to %s, handicap %s' %
                 (game.black_player, game.white_player, game.black_score, game.white_score,
                  game.handicap))
    template_values = {'game': game}
    self.response.out.write(template.render('addgame.html', template_values))
                
    
class ViewPlayer(webapp.RequestHandler): 
  def get(self):
    players = db.GqlQuery('SELECT * FROM Player WHERE player=:player',
                          player=self.request.get('player'))
    player = players[0]
    black_games = db.GqlQuery('SELECT * From Game WHERE black_player=:player',
                              player=player)
    white_games = db.GqlQuery('SELECT * From Game WHERE white_player=:player',
                              player=player)
    template_values = {'black_games': black_games, 'white_games': white_games,
                       'player': player}
    self.response.out.write(template.render('viewplayer.html', template_values))
    
application = webapp.WSGIApplication([('/', ViewLadder),
                                      ('/addplayer', AddPlayer),
                                      ('/addgame', AddGame),
                                      ('/viewplayer', ViewPlayer),
                                      ], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
